<template>
    <div>
        <el-breadcrumb separator="/" class="top-banner">
            <el-breadcrumb-item :to="{ path: '/recomSettingsIndex',query:{id:schoolId}}" class="top-banner-color">推荐管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加规则</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="edu-main">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="edu-ruleForm">
                <el-form-item label="所在校区：" >
                    <label for="">{{schoolName}}</label>
                </el-form-item>
                <el-form-item label="报名活动："  required prop="list">
                    <el-button type="primary" @click="dialogFormShow">选 择</el-button>
                    <el-input v-model="ruleForm.list" style="display:none"></el-input>
                    <el-table :data="tableData" style="width: 510px" class="martop20 activeTab">
                        <el-table-column  prop="enrollName" label="报名活动名称" class=""></el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="使用推荐码：" required class="reductionMoney" prop="reductionMoney">
                    减免学费
                     <el-input class="marleft10" type="number" v-model.number="ruleForm.reductionMoney" >
                        <template slot="prepend">￥</template>
                    </el-input>
                    <label for="" class="tip-txt">学员使用推荐码报名，减免的金额数</label>
                </el-form-item>
                <el-form-item label="推荐人奖励：" class="giveNum">
                    <el-form-item prop="giveFans">
                        <label for="">粉币：</label>
                        <el-input type="number" v-model.number="ruleForm.giveFans"></el-input>
                    </el-form-item>
                    <el-form-item class="martop20 giveNum">
                        <label for="">积分：</label>
                        <el-input v-model="ruleForm.giveIntegral" @keyup.native="onlyNumber(ruleForm,'giveIntegral')"></el-input>
                    </el-form-item>
                    <el-form-item class="martop20 giveNum" prop="giveCash">
                        <label for="">现金：</label>
                        <el-input type="number" v-model.number="ruleForm.giveCash">
                            <template slot="prepend">￥</template>
                        </el-input>
                        <label for="" class="tip-txt">成功推荐新用户报名即可获得三项奖励，不赠送的选项请填0或不填写</label>
                    </el-form-item>
                </el-form-item>
                 <el-form-item label="优惠叠加：" >
                    <el-switch v-model="ruleForm.overlap" active-value="0" inactive-value="1"></el-switch>
                    <label for="" class="tip-txt">开启推荐码与会员的卡券优惠叠加使用</label>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"  @click="submitForm('ruleForm')">保 存</el-button>
                    <el-button  @click="resetForm('ruleForm')">取 消</el-button>
                </el-form-item>
            </el-form>
        </div>
        <gt-transfer
            title="选择活动"
            :visible.sync="dialogFormVisible"
            width="80%"
            top="8vh"
            :data="tableData2"
            :selected.sync="param"
            :label="label"
            :prop="prop"
            :page-size="pageSize"
            :total="rowCount"
            @current-change="handleCurrentChange"
            @confirm="confirm"
            @cancel="cancel">
            <!-- @tapRemvoe="tapRemvoe"  @selection-change="handleSelectionChange" -->
            <div class="gt-transfer-search">
                <el-input placeholder="输入报名活动名称" class="width240" v-model="enrollName" @keyup.enter.native="handleIconClick">
                    <i slot="suffix" class="el-input__icon el-icon-search pointer" @click="handleIconClick"></i>
                </el-input>
            </div>
        </gt-transfer>
    </div>
</template>
<script>
import common from '@/assets/js/common'
export default {
  data(){
      var validateFans = (rule, value, callback) => {
          if(value){
              if(value < 0){
                  callback(new Error('请输入正确的数值'));
              }else{
                  callback()
              }
          }else{
              callback()
          }
      }
      return{
          tableData:[],
          tableData2:[],
          tableData3:[],
          ruleForm:{
            reductionMoney:'',
            giveIntegral:'',
            giveFans:'',
            giveCash:'',
            overlap:'1', //0 可以叠加  1不可以叠加
            schoolId:'',
            list:''
          },
          rules:{
              list:[
                  { required: true, message: '请选择至少一个活动'},
              ],
              reductionMoney:[
                { required: true, message: '请输入正确金额，0为不减免学费'},
                { min: 0, type:'number', message: '请输入正确金额，0为不减免学费'}
              ],
              giveFans:[
                 { validator: validateFans }
              ],
              giveCash:[
                 { validator: validateFans }
              ]
          },
          dialogFormVisible:false,
          currentPage:1,
          schoolName:'',
          schoolId:'',
          curPage:1,
          rowCount:1,
          pageCount:1,
          pageSize:10,
          enrollName:'',
          multipleSelection:[],
          param:[],
          enrollList:[],
          label:['报名活动名称','课程名称','价格','科目','开班时间'],
          prop:['enrollName','className','money','subjectName','startDate'],
          id:0,
          delArr:[]
      }
  },
  methods: {
         //验证 不能输入数字以外的东西
        onlyNumber(model,key){
            let that = this
            let num = parseFloat(event.target.value.replace(/\D/g,''));
            if(isNaN(num)){
                model[key] = 0
            }else{
                model[key] = num;
            }    
        },

        //transfer 穿梭框 相关事件
        confirm(val){
            let that = this
            let arr = [],newIds=[]
            this.tableData = val
            for(let i = 0; i < val.length; i++){
                newIds.push(val[i].id)
            }

            for(let i = 0; i < that.enrollList.length; i++){
                if(newIds.indexOf(that.enrollList[i].id) == -1){
                    arr.push(that.enrollList[i].id)
                }
            }
            that.delArr = arr
            console.log('arr===',arr)
            if(val.length >0){
                this.ruleForm.list = JSON.stringify(val)
            }else{
                this.ruleForm.list = ''
            }
            parent.window.postMessage("closeMask()", "*");   
        },
        cancel(){
            parent.window.postMessage("closeMask()", "*"); 
        },
        tapRemvoe(val,id){
            let that = this
            common.ajax({
                'url':eduAPI.activeAPI.delEnrollRecommend,
                'type': "POST",
                'data':{
                    enrollIds: id,
                    schoolId: that.schoolId
                },
                'success': function(data) {
                    console.log(data,'删除报名活动');
                   
                }
            });
            
        },
        handleSelectionChange(val,list){},
        //选择弹出层
        //请求选择活动列表数据
        activityList(curPage,enrollName){
            let that = this
            common.ajax({
                'url':eduAPI.activeAPI.findEnrollList,
                'type': "GET",
                'data':{
                    curPage: curPage,
                    enrollName:enrollName,
                    setRecommendId: that.id,
                    schoolId:that.schoolId
                },
                'success': function(data) {
                    console.log(data,'查询校区数据');
                    if (data.data) {
                        that.tableData2 = data.data.subList
                        that.rowCount = data.data.rowCount
                        that.pageCount = data.data.pageCount
                        that.pageSize = data.data.pageSize
                        for(let i in data.data.subList){
                            data.data.subList[i].startDate = common.formatTime(data.data.subList[i].startDate)
                        }
                    }else{
                        that.tableData2 = []
                    }
                }
            });
        },
        dialogFormShow(){
            let that = this
            that.dialogFormVisible = true
            parent.window.postMessage("openMask()", "*");
            that.activityList(1,that.enrollName)
        },
        //搜索活动
        handleIconClick(){
            this.activityList(this.curPage,this.enrollName)
        },
        handleCurrentChange(val,list) {
            let that = this
            that.curPage = val
            that.activityList(val,that.enrollName)
        },
        submitForm(formName) {
            let that = this
            if(that.ruleForm.enrollList){
                delete(that.ruleForm.enrollList)
            }
            console.log('ruleForm',that.ruleForm)
            // return
            that.$refs[formName].validate((valid) => {
            if (valid) {
                common.ajax({
                    'url': eduAPI.activeAPI.saveSetRecommend,
                    'type': "POST",
                    'data': that.ruleForm,
                    'success': function(data) {
                        console.log(data,'保存推荐规则');
                        //保存时删除报名活动
                        if(that.delArr.length>0){
                            common.ajax({
                                'url':eduAPI.activeAPI.delEnrollRecommend,
                                'type': "POST",
                                'data':{
                                    enrollIds: that.delArr.join(','),
                                    schoolId: that.schoolId
                                },
                                'success': function(data) {
                                    console.log(data,'删除报名活动成功');
                                }
                            });
                        }
                        that.$router.push({
                            name: "recomSettingsIndex", query:{id: that.schoolId} 
                        });
                    }
                });
            } else {
                console.log('error submit!!');
                return false;
            }
            });
            
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.tableData = []
        },
        toIndex(){
            this.$router.push({
                name: "recomSettingsIndex", query:{id: that.schoolId} 
            });
        }
  },
  mounted(){
      let that = this
      let router = this.$route.params;
      that.schoolId = router.schoolId;
      console.log(that.schoolId);
      console.log('------------bb')

      if(router.id!=''){
          that.id = router.id
      }else{
          that.id = 0
      }
      
      
      that.ruleForm['schoolId'] = router.schoolId
      //根据id查询校区
      common.ajax({
        'url': eduAPI.activeAPI.findAllSchoolList,
        'type': "GET",
        'success': function(data) {
            console.log(data,'查询校区数据');
            if (data.data) {
                for(let i in data.data){
                    if(data.data[i].id == that.schoolId){
                        that.schoolName = data.data[i].schoolName
                    }
                }
            }
            //编辑详情 
            common.ajax({
                'url':eduAPI.activeAPI.findSetRecommend,
                'type': "GET",
                'data':{
                    setRecommendIds:router.id,
                    schoolId: that.schoolId
                },
                'success': function(data) {
                    console.log(data,'编辑详情数据');
                    if (data.data) {
                        that.ruleForm = data.data
                        that.tableData = data.data.enrollList
                        that.param = data.data.enrollList
                        that.enrollList = data.data.enrollList
                        that.ruleForm.list = JSON.stringify(data.data.enrollList)
                    }
                }
            });
        }
    });
  }
}
</script>
<style scope lang="less">
.reductionMoney,.giveNum{
    position: relative;
}
.reductionMoney .el-form-item__error{
    left: 70px;
}
.giveNum .el-form-item__error{
    left: 45px;
}
.gt-transfer .gt-transfer-content{
    min-height: 450px
}
.gt-transfer .el-dialog__body{
    padding-top: 15px
}
.gt-transfer-search{
    margin-bottom: 20px
}
.activeTab {
    .cell{
        text-indent: 20px
    }
}
</style>
